(function(){
    angular.module('feibo.teacher.controller').controller('MiniClassController', MiniClassController);

    MiniClassController.$inject = ['TeacherService'];

    function MiniClassController(TeacherService){
        var vm = this;

        vm.data = {
            keyword: {
                name: false,
                fb_shift_category_name: false
            },
            list: undefined,
            bigClass: {}
        };

        vm.initData = function(){
            vm.fetchClassType();
        };

        vm.sorting = function(keyword){
            var data = vm.data;

            data.list.sort(function(a, b){
                var x, y;
                if(a && b && typeof a === 'object' && typeof b === 'object'){

                    if(data.keyword[keyword]){
                        x = a[keyword];
                        y = b[keyword];
                    }else {
                        x = b[keyword];
                        y = a[keyword];
                    }

                    if(x == y){
                        return 0;
                    }else if(typeof x === typeof y){
                        return  x >  y ? 1 : -1;
                    }else {
                        return typeof x > typeof y ? 1 : -1;
                    }
                }
            });

            data.keyword[keyword] = !data.keyword[keyword];
        };

        vm.fetchClassMiniType = function(){
            var queryConfig = {
                funcName: 'fetchClassMiniType',
                container: vm.data,
                propName: 'list',
                propChain: ['data','entries'],
                showLoadLayer: false
            };
            TeacherService.fetchClassMiniType(queryConfig).then(function(returnedData){
                if(returnedData.success){
                    returnedData.data.entries.forEach(function(val){
                        val.fb_shift_category_name = val.fb_shift_category_id ?
                                vm.data.bigClass[val.fb_shift_category_id] : '无关联大类';
                    });
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        vm.fetchClassType = function(isFirst){
            var queryConfig = {
                funcName: 'fetchClassType',
                propChain: [],
                showLoadLayer: false
            };

            TeacherService.fetchClassType(queryConfig).then(function(returnedData){
                vm.fetchClassMiniType();
                if(returnedData.success && returnedData.data && returnedData.data.entries){
                    // 构建大类对象
                    returnedData.data.entries.forEach(function(val){
                        this[val.id] = val.name;
                    }, vm.data.bigClass);
                }
            }).catch(function(error){
                console.error(error);
            });
        };
    }
}());
